<template>
	<div class="sessions">
		<el-tabs v-model="activeName" @tab-click="handleClick">
			<el-tab-pane label="会话记录" name="sessionsRecord">
				<SearchSession @reset="reset" @search="search" @export="exportAgentInfo" />
				<Table :tableData="sessionsData" @currentChange="viewUserData" class="session-table">
					<template v-slot:btn>
						<el-table-column width="310px" align="center" fixed="right" label="操作">
							<template slot-scope="scope">
								<el-button size="mini" type="primary" @click="viewInfo(scope.$index, scope.row)">查看详情</el-button>
								<el-button
									size="mini"
									type="danger"
									v-show="scope.row.hangUpTime === '' && (scope.row.isAccepted === '是' || scope.row.isConnect === '是')"
									@click="endSession(scope.$index, scope.row)"
									>强制结束</el-button
								>
								<el-button
									size="mini"
									type="success"
									v-show="scope.row.hangUpTime === '' && scope.row.media !== 'im' && scope.row.isConnect === '是'"
									@click="silentWatch(scope.$index, scope.row)"
									>静默观看</el-button
								>
							</template>
						</el-table-column>
					</template>
				</Table>
				<br />
				<PageSize :pages="checkData" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script>
import Table from '../components/Table.vue';
import PageSize from '../components/PageSize.vue';
import SearchSession from './SearchSession.vue';
import { dropsession, getRoomToken, getSessionRecordList, exportSessionList } from '@/api/api.js';
import { filterAgent, filterAiAgent } from '@/utils/filterAgents';

export default {
	components: {
		Table,
		PageSize,
		SearchSession
	},
	data() {
		return {
			activeName: 'sessionsRecord',
			checkData: {
				page: 1,
				pageSize: 10,
				total: 0,
				endDialingTime: '',
				startDialingTime: '',
				isAccepted: '',
				isRinging: '',
				isStucked: '',
				isNoPicture: '',
				isGiveUpQueued: '',
				type: '', //通话模式：normal:正常 transfer：转接
				sessionId: '',
				userName: '',
				score: '', // 评分
				summaryIsCompleted: '' // 会话小结是否完成
			},
			sessionsData: {
				sort: { prop: 'startDialingTime', order: 'descending' },
				tableHead: [
					{
						label: 'Session ID',
						prop: 'sessionId',
						width: '150px'
					},
					{
						label: 'AI 坐席工号',
						prop: 'aiAgentId',
						width: '120px'
					},
					{
						label: '人工坐席工号',
						prop: 'agentId',
						width: '120px'
					},
					{
						label: '姓名',
						prop: 'fullName',
						width: '100px'
					},
					{
						label: '是否接听',
						prop: 'isAccepted',
						width: '80px'
					},
					{
						label: '是否接通',
						prop: 'isConnect',
						width: '80px'
					},
					{
						label: '呼叫业务场景',
						prop: 'scenarioName',
						width: '120px'
					},
					{
						label: '拨号开始时间',
						prop: 'startDialingTime',
						width: '150px'
					},
					{
						label: '拨号时长',
						prop: 'calliDuration'
					},
					{
						label: '是否派工',
						prop: 'isRinging'
					},
					{
						label: '派工时间',
						prop: 'latestRingingTime',
						width: '150px'
					},
					{
						label: '会话方式',
						prop: 'type'
					},
					{
						label: '是否卡顿',
						prop: 'isStucked'
					},
					{
						label: '会话无画面',
						prop: 'isNoPicture'
					},
					{
						label: '是否排队放弃',
						prop: 'isGiveUpQueued',
						width: '120px'
					},
					{
						label: '会话开始时间',
						prop: 'acceptedTime',
						width: '150px'
					},
					{
						label: '会话结束时间',
						prop: 'hangUpTime',
						width: '150px'
					},
					{
						label: '会话时长',
						prop: 'servingDuration'
					},
					{
						label: '会话类型',
						prop: 'media',
						width: '120px'
					},
					{
						label: '会话建立失败原因',
						prop: 'failReason',
						width: '120px'
					},
					{
						label: '录像是否完整',
						prop: 'isRecordComplete'
					},
					{
						label: '会话小结',
						prop: 'summaryIsCompleted'
					},
					{
						label: '评价',
						prop: 'score'
					},
					{
						label: '评价内容',
						prop: 'leavingMessage',
						width: 300,
						tooltip: true
					}
				],
				tableConent: [],
				showIndex: true
			}
		};
	},
	mounted() {
		this.getSessionList();
	},

	methods: {
		// 初始化获取 sessions 数据
		async getSessionList() {
			this.$Spin.show();
			try {
				const { data } = await getSessionRecordList(this.checkData);
				console.log(data, '会话记录');
				if (data.code === 200) {
					this.sessionsData.tableConent = this.getInfoData(data.data.data);
				} else {
					console.log('获取会话记录', data);
				}
				this.checkData.total = data.data.total;
				this.$Spin.hide();
			} catch (err) {
				console.log('getSessionList error', err);
				this.$requestApiError(err, () => {
					this.$router.push('/');
				});
				this.$Spin.hide();
			}
		},

		// 改变每页条数
		changePageSize(val) {
			this.checkData.pageSize = val;
			this.getSessionList();
		},
		// 改变当前页数
		changeCurrentPage(val) {
			this.checkData.page = val;
			this.getSessionList();
		},
		// 查看详情
		viewInfo(index, row) {
			console.log(index, row);
			let routerdata = this.$router.resolve({
				name: 'session'
			});
			let newhref = routerdata.href + '?sessionId=' + row.sessionId + '&uid=' + window.uid;
			// console.log(newhref);
			window.open(newhref, '_blank');
		},
		// 通话开始时间
		searchStartTime() {
			this.$nextTick(() => {
				if (this.checkData.startDialingTime) {
					this.checkData.startDialingTime = this.checkData.startDialingTime.toISOString();
				} else {
					this.checkData.startDialingTime = '';
				}
				this.checkData.page = 1;
				this.checkData.pageSize = 10;
				this.getSessionList();
			});
		},
		// 通话结束时间
		searchEndTime() {
			this.$nextTick(() => {
				if (this.checkData.endDialingTime) {
					this.checkData.endDialingTime = this.checkData.endDialingTime.toISOString();
				} else {
					this.checkData.endDialingTime = '';
				}
				this.checkData.page = 1;
				this.checkData.pageSize = 10;
				this.getSessionList();
			});
		},
		// 强制结束会话
		endSession(index, row) {
			this.$confirm(`确定要结束: ${row.sessionId} 会话吗, 是否继续?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					dropsession(row.sessionId)
						.then(res => {
							if (res.status === 200) {
								this.$message({
									type: 'success',
									message: '结束会话成功!'
								});
								this.getSessionList();
							}
						})
						.catch(err => {
							this.$requestApiError(err, () => {
								this.$router.push('/');
							});
						});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					});
				});
		},

		/*进入房间查看房间里当前的流信息*/
		silentWatch(index, row) {
			let self = this;
			getRoomToken(row.roomId, name)
				.then(function (resp) {
					if (resp.status === 200) {
						let data = resp.data;
						let routerdata = self.$router.resolve({
							name: 'jmgk'
						});
						let newhref = routerdata.href + '?roomId=' + row.roomId + '&token=' + data + '&uid=' + window.uid;
						window.open(newhref, '_blank');
					} else {
						self.$message.error('silent watch error,', resp.statusText);
					}
				})
				.catch(function (error) {
					console.log('get room token error', error, error.response);
					self.$message.error('静默观战失败！');
				});
		},
		reset(data) {
			console.log(data, 'reset');
			data.startDialingTime = '';
			data.endDialingTime = '';
			data.isAccepted = '';
			data.isRinging = '';
			data.isStucked = '';
			data.isNoPicture = '';
			data.isGiveUpQueued = '';
			data.type = '';
			data.sessionId = '';
			data.userName = '';
			data.score = '';
			data.summaryIsCompleted = '';
		},
		search(data) {
			console.log('search:', data);
			this.checkData.startDialingTime = data.startDialingTime;
			this.checkData.endDialingTime = data.endDialingTime;
			this.checkData.isAccepted = data.isAccepted;
			this.checkData.isRinging = data.isRinging;
			this.checkData.isStucked = data.isStucked;
			this.checkData.isNoPicture = data.isNoPicture;
			this.checkData.isGiveUpQueued = data.isGiveUpQueued;
			this.checkData.type = data.type;
			this.checkData.sessionId = data.sessionId;
			this.checkData.userName = data.userName;
			this.checkData.page = 1;
			this.checkData.score = data.score;
			this.checkData.summaryIsCompleted = data.summaryIsCompleted;
			this.getSessionList();
		},
		// 是否派工，是否卡顿，是否无画面，是否排队放弃  根据状态返回是和否
		getStatusYesNo(value) {
			let result = '';
			switch (value) {
				case 1:
					result = '是';
					break;
				case 0:
					result = '否';
					break;
				case null:
					result = '-';
					break;
				default:
					result = '-';
					break;
			}
			return result;
		},
		// 筛接口返回的数据
		getInfoData(array) {
			return array.map(item => {
				let fullNameList = [];
				// 过滤掉多次加入的账户
				item.invitations.forEach(value => {
					// 默认 invitations 中的信息顺序是按接入会话的顺序
					let hasAdded = false;
					for (let i = 0; i < fullNameList.length; i++) {
						if (fullNameList[i].assignedAgentId === value.assignedAgentId) {
							hasAdded = true;
							// 防止用户改名，这里赋最新值
							fullNameList[i] = value;
							break;
						}
					}
					if (!hasAdded) {
						fullNameList.push(value);
					}
				});
				// 重置为姓名列表
				fullNameList = fullNameList
					.filter(value => {
						return !value.isRobot && value.fullName;
					})
					.map(value => {
						return value.fullName;
					});
				return {
					fullName: fullNameList.length > 0 ? fullNameList.toString() : '-',
					media: item.media,
					servingDuration: item.servingDuration || '-',
					hangUpTime: item.hangUpTime,
					acceptedTime: item.acceptedTime || '-',
					calliDuration: item.calliDuration || '-',
					startDialingTime: item.startDialingTime,
					isAccepted: item.isAccepted ? '是' : '否',
					isConnect: item.media === 'im' ? (item.isAccepted ? '是' : '否') : item.audioVideoCallIsConnected === null ? item.isConnect : item.audioVideoCallIsConnected ? '是' : '否',
					agentId: filterAgent(item.invitations) || '-',
					aiAgentId: filterAiAgent(item.invitations) || '-',
					sessionId: item.sessionId,
					roomId: item.roomId,
					isRinging: this.getStatusYesNo(item.isRinging),
					type: item && item.type === 'normal' ? '初始会话' : item && item.type === 'transfer' ? '场景转接' : '-',
					isStucked: this.getStatusYesNo(item.isStucked),
					isNoPicture: this.getStatusYesNo(item.isNoPicture),
					isGiveUpQueued: this.getStatusYesNo(item.isGiveUpQueued),
					media: item.media === 'imUpgradeVideo' ? 'IM升级video' : item.media === 'imUpgradeAudio' ? 'IM升级audio' : item.media,
					scenarioName: item?.scenarioName ? item?.scenarioName : '-',
					latestRingingTime: item?.latestRingingTime ? this.$moment(item?.latestRingingTime).format('YYYY-MM-DD HH:mm:ss') : '-', //派工时间（第一次振铃时间）
					failReason: this.getFailReasonStatus(item?.failReason),
					isRecordComplete: item?.recordingHasFail === 0 ? '是' : item?.recordingHasFail === null ? '-' : '否',
					summaryIsCompleted: item.summaryIsCompleted === 'Y' ? '已完成' : item.summaryIsCompleted === 'N' ? '未完成' : '-',
					score: item.score ? this.getScore(item.score) : '-',
					leavingMessage: item.suggestion || '-'
				};
			});
		},

		getScore(score) {
			console.log('score', score);
			score = score.toString();
			let result = '';
			switch (score) {
				case '1':
					result = '非常不满意';
					break;
				case '2':
					result = '不满意'; //(没有找到在线的，并且签入了业务场景对应的坐席)
					break;
				case '3':
					result = '一般';
					break;
				case '4':
					result = '满意';
					break;
				case '5':
					result = '非常满意';
					break;
				default:
					result = '-';
					break;
			}
			return result;
		},
		getFailReasonStatus(status) {
			console.log('getFailReasonStatus:', status);
			let result = '';
			switch (status) {
				case 'canceled':
					result = '访客取消呼叫';
					break;
				case 'notfound':
					result = '未找到坐席'; //(没有找到在线的，并且签入了业务场景对应的坐席)
					break;
				case 'timeout':
					result = '呼叫超时';
					break;
				case 'offday':
					result = '不在工作日';
					break;
				case 'offtime':
					result = '不在工作时间';
					break;
				case 'scenariodisabled':
					result = '业务场景未启用';
					break;
				case 'otherCustomerAccept':
					result = '其他坐席已经接听';
					break;
				case 'multiCustomerForbidAI':
					result = '指定机器人呼叫时会话中存在多访客';
					break;
				case 'rejected':
					result = '坐席拒绝';
					break;
				case 'ringingTimeout':
					result = '振铃超时';
					break;
				case 'customerRolesEmpty':
					result = '访客角色为空';
					break;
				case 'scenarioRolesEmpty':
					result = '呼叫的业务场景角色为空';
					break;
				case 'scenarioRolesNotMatched':
					result = ' 业务场景角色不匹配';
					break;
				case 'ban':
					result = '命中黑名单';
					break;
				default:
					result = '-';
					break;
			}
			return result;
		},
		/** 导出表格数据 */
		async exportAgentInfo(data) {
			this.checkData.startDialingTime = data.startDialingTime;
			this.checkData.endDialingTime = data.endDialingTime;
			this.checkData.isAccepted = data.isAccepted;
			this.checkData.isRinging = data.isRinging;
			this.checkData.isStucked = data.isStucked;
			this.checkData.isNoPicture = data.isNoPicture;
			this.checkData.isGiveUpQueued = data.isGiveUpQueued;
			this.checkData.type = data.type;
			this.checkData.sessionId = data.sessionId;
			this.checkData.userName = data.userName;
			this.checkData.score = data.score;
			this.checkData.summaryIsCompleted = data.summaryIsCompleted;
			this.exportWorkOrder();
		},
		exportWorkOrder() {
			// 先去掉时间限制
			// if (!this.checkData.startTime || !this.checkData.endTime) {
			// 	this.$message.error('请选择开始时间和结束时间');
			// 	return;
			// }
			exportSessionList(this.checkData)
				.then(resp => {
					if (resp) {
						const blob = new Blob([resp.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
						const fileName = `${new Date().getTime()}-服务记录列表数据` + '.xlsx';
						saveAs(blob, fileName, { autoBom: false });
					} else {
						console.warn('exportWorkOrder ', resp);
					}
				})
				.catch(e => {
					console.error('exportWorkOrder e', e);
				});
		},
	}
};
</script>

<style lang="less" scoped>
.time {
	color: #666;
	padding-bottom: 20px;
}

.session-table {
	margin-top: 30px;
}
</style>

<style lang="less">
.time {
	.el-date-editor {
		input {
			height: 32px;
		}

		.el-input__icon {
			line-height: 32px;
		}
	}
}
</style>
